import 'package:dio/dio.dart';
import 'dart:async';

/*
 * 封装 restful 请求
 *
 * GET、POST、DELETE、PATCH
 * 主要作用为统一处理相关事务：
 *  - 统一处理请求前缀；
 *  - 统一打印请求信息；
 *  - 统一打印响应信息；
 *  - 统一打印报错信息；
 */
class Request {
  /// global dio object
  static Dio dio;

  /// default options
  static const String API_PREFIX = 'http://192.168.112.159:8083';
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';


  /// 创建 dio 实例对象
  static Dio createInstance() {
    if (dio == null) {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
      var options = BaseOptions(
        connectTimeout: 15000,
        receiveTimeout: 15000,
        responseType: ResponseType.json,
        validateStatus: (status) {
          // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
          return true;
        },
        baseUrl: API_PREFIX,
      );

      dio = new Dio(options);
    }

    return dio;
  }

  ///Get请求测试
  static void getHttp() async {
    try {
      Response response = await Dio().get("http://www.google.cn");
      print("response$response");
    } catch (e) {
      print(e);
    }
  }

  ///Post请求测试
  static void postHttp<T>( String url, parameters, String method) async {

    ///定义请求参数
    parameters = parameters ?? {};
    //参数处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    try {
      Response response;
      Dio dio = createInstance();
      response = await dio.post(url, data: parameters);
      print('响应数据：' + response.toString());
      if (response.statusCode == 200) {
        String code = response.data ? response.data.code : "404";
        if(code=="0"){
          return response.data.data;
        }else if(code=="1"){
          throw Exception('错误提示:${response.data.msg}');
        }else{
          throw Exception('没有返回状态码');
        }
      } else {
        throw Exception('异常statusCode:${response.statusCode}');
      }
    } catch (e) {
      print('请求出错：' + e.toString());
      // onError(e.toString());
    }
  }

  /// request method
  //url 请求链接
  //parameters 请求参数
  //metthod 请求方式
  //onSuccess 成功回调
  //onError 失败回调
  static Future<Map> request<T>(String url,parameters,method) async {
    parameters = parameters ?? {};
    method = method ?? 'GET';

    //url = API_PREFIX +url;
    /// 打印:请求地址-请求方式-请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + parameters.toString());
    print(API_PREFIX);
    var res;
    dio = createInstance();
    // Dio dio = new Dio();
    try {
      Response response = await dio.request(url,
          data: parameters, options: Options(method: method));
      print(response);
      print(response.statusCode);
      if (response.statusCode == 200) {
        String code = response.data["code"] ?? "404";
        if(code=="0"){
          res = response.data["data"];
        }else if(code=="1"){
          String msg = response.data["msg"];
          throw Exception('错误提示:$msg');
        }else{
          throw Exception('没有返回状态码');
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
    }
    return res;
  }

  /// 清空 dio 对象
  static clear() {
    dio = null;
  }
}